package com.zhou.consulconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zx
 * @date 2019/7/10 15:17
 */
@RestController
public class DcController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer")
    public String dc() {
        List<ServiceInstance> instances = discoveryClient.getInstances("consul-client");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
        System.out.println(url);
//        ServiceInstance choose = loadBalancerClient.choose("consul-client");
//        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/dc";
//        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }

}
